package com.geostar.constructionland.index.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.geostar.constructionland.index.entity.IndexWithholdRecordEntity;
import com.geostar.constructionland.index.entity.InxOutStorageAcotEntity;
import com.geostar.constructionland.index.entity.LandUseIndexEntity;
import com.geostar.constructionland.index.entity.model.IndexWithholdModel;
import com.geostar.constructionland.index.mapper.IndexWithholdMapper;
import com.geostar.constructionland.index.mapper.InxOutStorageAcotMapper;
import com.geostar.constructionland.index.mapper.LandUseIndexMapper;
import com.geostar.constructionland.index.service.IndexWithholdService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class IndexWithholdSerImpl implements IndexWithholdService {

    @Resource
    InxOutStorageAcotMapper inxOutStorageAcotMapper;
    @Resource
    IndexWithholdMapper indexWithholdMapper;
    @Resource
    LandUseIndexMapper landUseIndexMapper;

    /**
     * 指标预扣
     * @param indexWithholdModel
     * @return
     */
    @Override
    @Transactional
    public String indexWithhold(IndexWithholdModel indexWithholdModel) {
        //获取ywid
        String businessId = indexWithholdModel.getBusinessId();
        //获取预扣类型（保存为出库状态）
        String indexWithholdType = indexWithholdModel.getIndexWithholdType();
        //判断出库台账是否存在数据（此处引用于检查业务日志，不进行出库台账数据查询）
        int hasOutStorage = isIndexOutStorage(businessId);
        if(hasOutStorage==1) {
            //查询出库数据，用于保存业务日志。
            QueryWrapper<InxOutStorageAcotEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ywid",businessId);
            List<InxOutStorageAcotEntity> outStorageData = inxOutStorageAcotMapper.selectList(queryWrapper);
            if("03".equals(indexWithholdType)) {
                //保存业务日志并删除出库记录
                saveLogAndDelete(indexWithholdModel,outStorageData);
            }
            else{
                //保存业务日志并修改出库状态
                saveLogAndUpdate(indexWithholdModel, outStorageData);
            }
        }else if(hasOutStorage==0) {
            //设置预扣
            indexWithholdModel.setIndexWithholdType("01");
            //保存业务日志并指标出库（jsyd_ydzb->jsyd_zbcktz)
            indexOutStroage(indexWithholdModel);
        }else {
            return "IndexWithholdSerImpl.isIndexOutStorage()方法检测异常！";
        }
        return "true";
    }

    /**
     * 判断出库台账是否存在数据
     * @return
     */
    private int isIndexOutStorage(String businessId) {
        String judge = indexWithholdMapper.isIndexOutStorage(businessId);
        if("1".equals(judge)) {
            return 1;//存在数据
        }else if("0".equals(judge)) {
            return 0;//不存在数据
        }else{
            return -1;//异常
        }
    }

    /**
     * 保存业务日志并删除出库记录
     */
    private void saveLogAndDelete(IndexWithholdModel indexWithholdModel,
                                  List<InxOutStorageAcotEntity> listOutStorage) {
        //保存日志
        IndexWithholdRecordEntity indexWithholdRecord = new IndexWithholdRecordEntity();
        indexWithholdRecord.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        indexWithholdRecord.setBusinessId(indexWithholdModel.getBusinessId());
        indexWithholdRecord.setInxOutStorageType(indexWithholdModel.getIndexWithholdType());
        indexWithholdRecord.setUserId(indexWithholdModel.getUserId());
        indexWithholdRecord.setUserName(indexWithholdModel.getUserName());
        indexWithholdRecord.setCodeTrack(indexWithholdModel.getCodeTrack());
        indexWithholdRecord.setInxOutStorageAcotEntity(listOutStorage.toString());
        indexWithholdRecord.setRemark("");
        indexWithholdRecord.setOPTYPE("saveLogAndDelete");
        indexWithholdMapper.insert(indexWithholdRecord);
        //删除出库记录
        UpdateWrapper<InxOutStorageAcotEntity> updateWrapper = new UpdateWrapper<InxOutStorageAcotEntity>();
        updateWrapper.eq("ywid", indexWithholdModel.getBusinessId());
        int resultNum = inxOutStorageAcotMapper.delete(updateWrapper);
        if(resultNum!=listOutStorage.size()){
            throw new RuntimeException("删除数据与查询数据不一致");
        }
    }

    /**
     * 保存业务日志并修改出库状态
     */
    private void saveLogAndUpdate(IndexWithholdModel indexWithholdModel,
                                  List<InxOutStorageAcotEntity> listOutStorage) {
        //保存日志
        IndexWithholdRecordEntity indexWithholdRecord = new IndexWithholdRecordEntity();
        indexWithholdRecord.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        indexWithholdRecord.setInxOutStorageType(indexWithholdModel.getIndexWithholdType());
        indexWithholdRecord.setBusinessId(indexWithholdModel.getBusinessId());
        indexWithholdRecord.setUserName(indexWithholdModel.getUserName());
        indexWithholdRecord.setUserId(indexWithholdModel.getUserId());
        indexWithholdRecord.setCodeTrack(indexWithholdModel.getCodeTrack());
        indexWithholdRecord.setInxOutStorageAcotEntity(listOutStorage.toString());
        indexWithholdRecord.setRemark("");
        indexWithholdRecord.setOPTYPE("saveLogAndUpdate");
        indexWithholdMapper.insert(indexWithholdRecord);
        //修改出库状态
        UpdateWrapper<InxOutStorageAcotEntity> updateWrapper = new UpdateWrapper<InxOutStorageAcotEntity>();
        updateWrapper.eq("ywid", indexWithholdModel.getBusinessId());
        InxOutStorageAcotEntity inxOutStorageAcotEntity = new InxOutStorageAcotEntity();
        inxOutStorageAcotEntity.setOutStorageStatus(indexWithholdModel.getIndexWithholdType());
        int resultNum = inxOutStorageAcotMapper.update(inxOutStorageAcotEntity,updateWrapper);
        if(resultNum!=listOutStorage.size()){
            throw new RuntimeException("修改数据与查询数据不一致");
        }
    }

    /**
     * 保存业务日志并指标出库
     */
    private void indexOutStroage(IndexWithholdModel indexWithholdModel) {
        //查询选取指标
        QueryWrapper<LandUseIndexEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ywid", indexWithholdModel.getBusinessId());
        List<LandUseIndexEntity> landUseIndexList = landUseIndexMapper.selectList(queryWrapper);
        //保存日志
        IndexWithholdRecordEntity indexWithholdRecord = new IndexWithholdRecordEntity();
        indexWithholdRecord.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        indexWithholdRecord.setInxOutStorageType(indexWithholdModel.getIndexWithholdType());
        indexWithholdRecord.setBusinessId(indexWithholdModel.getBusinessId());
        indexWithholdRecord.setUserName(indexWithholdModel.getUserName());
        indexWithholdRecord.setUserId(indexWithholdModel.getUserId());
        indexWithholdRecord.setCodeTrack(indexWithholdModel.getCodeTrack());
        indexWithholdRecord.setRemark("");
        indexWithholdRecord.setOPTYPE("indexOutStroage");
        indexWithholdRecord.setInxOutStorageAcotEntity(landUseIndexList.toString());
        indexWithholdMapper.insert(indexWithholdRecord);
        //指标出库
        int landUseIndexNum = landUseIndexList.size();
        for(int i=0; i<landUseIndexNum; i++) {
            LandUseIndexEntity landUseIndexEntity = landUseIndexList.get(i);
            InxOutStorageAcotEntity inxOutStorageAcotEntity = new InxOutStorageAcotEntity();
            //主键
            inxOutStorageAcotEntity.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            //入库ID
            inxOutStorageAcotEntity.setInxStorageIAcotId(landUseIndexEntity.getInxStorageIAcotId());
            //新增建设用地
            inxOutStorageAcotEntity.setBuildLandAdd(landUseIndexEntity.getAddIndex());
            //农用地
            inxOutStorageAcotEntity.setAgclLand(landUseIndexEntity.getAgclLandIndex());
            //耕地
            inxOutStorageAcotEntity.setFarmland(landUseIndexEntity.getFarmlandIndex());
            //出库状态
            inxOutStorageAcotEntity.setOutStorageStatus(indexWithholdModel.getIndexWithholdType());
            //操作人ID
            inxOutStorageAcotEntity.setOperatorId(indexWithholdModel.getUserId());
            //操作时间
            inxOutStorageAcotEntity.setOperatorTime(new Date());
            //业务ID
            inxOutStorageAcotEntity.setBusinessId(landUseIndexEntity.getBusinessId());
            //备注
            inxOutStorageAcotEntity.setRemark("");
            //出库类型(xtsp：系统审批)
            inxOutStorageAcotEntity.setOutStorageType("xtsp");
            //出库时间
            inxOutStorageAcotEntity.setOutStorageTime(new Date());
            //插入数据
            inxOutStorageAcotMapper.insert(inxOutStorageAcotEntity);
        }
    }

}
